<template>
	<view class="wraper">
		<wd-sidebar v-model="active" @change="handleChange" class="aside">
			<wd-sidebar-item v-for="(item, index) in categories" :key="index" :value="index" :label="item.label"
				:disabled="item.disabled" />
		</wd-sidebar>
		<view class="content">
			<view class="brand-section">
				<view class="brand-title">品牌筛选</view>
				<view class="brand-list">
					<view class="brand-item" v-for="(item, index) in brands" :key="index">
						<up-tag :text="item.text" :plain="!item.checked" type="success" shape="circle" :name="index"
							@click="radioClick" class="brand-tag">
						</up-tag>
					</view>
					<view class="empty-brand" v-if="brands.length === 0 && !loadingBrand">
						暂无品牌信息
					</view>
				</view>
			</view>

			<view class="goods-section" v-if="brands.length > 0">
				<up-list @scrolltolower="scrolltolower" v-if="hasLoaded">
					<up-list-item v-for="(item, index) in goodslist" :key="item.proid || index"
						@click="gotoDetail(item.proid)">
						<view class="goods-item-container">
							<image :src="item.img1 || ''" class="goods-image" mode="aspectFill"></image>
							<view class="goods-content">
								<view class="goods-name" :class="{ 'text-ellipsis': true }">
									{{ item.proname || '商品信息' }}
								</view>
								<view class="goods-info-bottom">
									<view class="goods-price" v-if="item.originprice && item.discount">
										<text
											class="current-price">¥{{ (item.originprice * item.discount / 100).toFixed(2) }}</text>
										<text class="original-price"
											v-if="item.originprice > (item.originprice * item.discount / 100)">
											¥{{ item.originprice }}
										</text>
									</view>
									<view class="goods-stock" v-if="item.stock !== undefined">
										库存：{{ item.stock }}件
									</view>
								</view>
							</view>
						</view>
					</up-list-item>

					<up-loadmore v-if="hasLoaded && goodslist.length > 0" :status="loadStatus"
						class="load-more"></up-loadmore>

					<view v-if="goodslist.length === 0 && !loadingGoods && hasLoaded" class="empty-goods">
						暂无商品
					</view>
				</up-list>

				<view v-if="brands.length > 0 && goodslist.length === 0 && loadingGoods" class="loading-goods">
					加载中...
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		nextTick,
		watchEffect
	} from 'vue'
	import http from '/utils/request.js'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		setTabBarBadge
	} from "/utils/tabBarHelper.js";

	const active = ref(0)
	const scrollTop = ref(0)
	const categories = ref([])
	const brands = ref([])
	const goodslist = ref([])
	const checkedCategory = ref('')
	const checkedBrand = ref('')
	const count = ref(1)
	const limitNum = ref(10)
	const loadingBrand = ref(false)
	const loadingGoods = ref(false)
	const hasLoaded = ref(false)
	const loadStatus = ref('loadmore')

	async function getCategoryList() {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})

		try {
			const res = await http.get('/pro/categorylist')
			categories.value = res.data.map((item, index) => ({
				label: item || '无数据',
				title: `标题${index + 1}`,
				disabled: false
			}))
		} catch (err) {
			console.error('加载失败:', err)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	async function getBrandList(category) {
		if (!category) {
			brands.value = []
			return
		}

		loadingBrand.value = true
		try {
			const res = await http.get('/pro/categorybrandlist', {
				category
			})
			brands.value = res.data
				.filter(item =>
					item?.brand && typeof item.brand === 'string' && item.brand.trim() !== ''
				)
				.map((item, index) => ({
					text: item.brand,
					checked: index === 0
				}))
			if (brands.value.length > 0 && !checkedBrand.value) {
				checkedBrand.value = brands.value[0].text
			}
		} catch (err) {
			console.error('获取品牌列表失败:', err)
			brands.value = []
		} finally {
			loadingBrand.value = false
		}
	}

	async function getProductList() {
		if (!checkedCategory.value || !checkedBrand.value) {
			goodslist.value = []
			hasLoaded.value = true
			loadingGoods.value = false
			return
		}

		uni.showLoading({
			title: '加载中...',
			mask: true
		})

		loadingGoods.value = true
		loadStatus.value = 'loadmore'
		hasLoaded.value = false

		try {
			const res = await http.get('/pro/categorybrandprolist', {
				count: count.value,
				limitNum: limitNum.value,
				category: checkedCategory.value,
				brand: checkedBrand.value
			})

			if (res.data && Array.isArray(res.data)) {
				const goods = res.data
					.filter(item => {
						return item.proname && item.proname.trim() !== '' && item.originprice !== undefined
					})
					.map((item, index) => ({
						proid: item.proid || '',
						proname: item.proname || '',
						img1: item.img1 || '',
						originprice: item.originprice,
						discount: item.discount,
						stock: item.stock,
						...item
					}))

				if (loadStatus.value === 'loadmore') {
					goodslist.value = [...goodslist.value, ...goods]
				} else {
					goodslist.value = goods
				}

				hasLoaded.value = true

				if (goodslist.value.length === 0) {
					loadStatus.value = 'nomore'
				} else if (goodslist.value.length < limitNum.value) {
					loadStatus.value = 'nomore'
				} else {
					loadStatus.value = 'loadmore'
				}
			} else {
				goodslist.value = []
				hasLoaded.value = true
				loadStatus.value = 'nomore'
			}
		} catch (err) {
			console.error('获取商品列表失败:', err)
			goodslist.value = []
			hasLoaded.value = true
			loadStatus.value = 'nomore'
		} finally {
			loadingGoods.value = false
			uni.hideLoading()
		}
	}

	const radioClick = (name) => {
		brands.value.forEach((item, index) => {
			item.checked = index === name;
		});
		checkedBrand.value = brands.value[name]?.text || ''
	}

	function handleChange({
		value
	}) {
		active.value = value
		scrollTop.value = 0
		checkedCategory.value = categories.value[value].label
	}

	const debounce = (fn, delay = 300) => {
		let timer = null;
		return (...args) => {
			if (timer) clearTimeout(timer);
			timer = setTimeout(() => fn.apply(this, args), delay);
		};
	};

	const scrolltolower = debounce(() => {
		if (loadStatus.value === 'loadmore' && hasLoaded.value && !loadingGoods.value) {
			loadmore();
		}
	}, 300);

	const loadmore = () => {
		if (loadingGoods.value || loadStatus.value !== 'loadmore') return;

		loadingGoods.value = true;
		count.value++
		loadStatus.value = 'loading'
		getProductList().finally(() => {
			if (!loadingGoods.value) return;
			loadingGoods.value = false;
		});
	}

	const gotoDetail = (proid) => {
		uni.navigateTo({
			url: `/pages/goods-detail/goods-detail?proid=${proid}`
		})
	}

	watchEffect(() => {
		checkedCategory.value = categories.value[active.value]?.label || ''
		checkedBrand.value = ''
		getBrandList(checkedCategory.value)
	})

	watchEffect(() => {
		if (checkedBrand.value) {
			goodslist.value = []
			getProductList()
		}
	})

	onLoad(() => {
		getCategoryList().then(() => {
			if (categories.value.length) {
				checkedCategory.value = categories.value[0]?.label || ''
				getBrandList(checkedCategory.value)
			}
		})
	})

	onShow(() => {
		setTabBarBadge()
	})
</script>

<style>
	.wraper {
		display: flex;
		height: calc(100vh - var(--window-top));
		height: calc(100vh - var(--window-top) - constant(safe-area-inset-bottom));
		height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom));
		overflow: hidden;
	}

	.aside {
		min-width: 200rpx;
		background: #f8f8f8;
	}

	.content {
		flex: 1;
		background: #fff;
		display: flex;
		flex-direction: column;
	}

	.brand-section {
		padding: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.brand-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.brand-list {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
		max-height: 200rpx;
		overflow-y: auto;
	}

	.brand-item {
		flex-shrink: 0;
	}

	.brand-tag {
		margin: 0 !important;
	}

	.goods-section {
		flex: 1;
		overflow: hidden;
	}

	.goods-item-container {
		display: flex;
		padding: 20rpx;
		background: #fff;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.goods-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.goods-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		min-width: 0;
	}

	.goods-name {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		line-height: 1.4;
		margin-bottom: 15rpx;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.goods-info-bottom {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		width: 100%;
	}

	.goods-price {
		display: flex;
		align-items: baseline;
		gap: 10rpx;
	}

	.current-price {
		color: #ff4757;
		font-size: 30rpx;
		font-weight: bold;
	}

	.original-price {
		color: #999;
		font-size: 24rpx;
		text-decoration: line-through;
	}

	.goods-stock {
		color: #666;
		font-size: 24rpx;
	}

	.empty-brand {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx 20rpx;
		color: #999;
		font-size: 26rpx;
	}

	.empty-goods {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 100rpx 20rpx;
		color: #999;
		font-size: 28rpx;
	}

	.loading-goods {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 100rpx 20rpx;
		color: #999;
		font-size: 28rpx;
	}

	.load-more {
		padding: 20rpx;
	}

	:deep(.up-list-item) {
		padding: 0 !important;
		background: transparent;
	}

	:deep(.up-cell) {
		padding: 0 !important;
		background: transparent;
		border: none;
	}

	:deep(.up-cell__title) {
		padding: 0;
	}

	.wraper ::v-deep .wd-sidebar-item--active::before {
		background-color: #42b983;
		will-change: background-color;
	}

	.wraper ::v-deep .wd-sidebar-item--active {
		color: #42b983;
		transition: color 0.2s ease;
	}
</style>